<template>
  <div class="writer">
    <div class="right">
      <el-input v-model="input" placeholder="请输入需要绘制的地址">
        <template slot="prepend">Http://</template>
      </el-input>
      <div>
        <el-button @click="write" type="success">绘制</el-button>
        <el-upload
          class="upload"
          action
          accept="image/*"
          :http-request="uploadImg"
          :multiple="false"
          :show-file-list="false"
        >
          <el-button type="success">上传</el-button>
        </el-upload>
        <el-button @click="save" type="success">保存</el-button>
      </div>
      <mango-qr-code
        :base="'mmangoo'"
        ref="qrCode"
        :loading="writing"
        v-if="writing"
        :Url="'http://' + `${input}`"
        :width="240"
        :height="240"
        :Src="imageUrl"
      >
        <template class="desc" v-slot:description="message">
          请在上方输入网址即可重新绘制二维码↑
          <br />
          <div>{{ message }}</div>
          支持个性化图片上传与二维码保存
          <br />
          点击保存可以将二维码保存到本地
        </template>
        <template #button> 1 </template>
      </mango-qr-code>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      input: 'www.baidu.com',
      writing: true,
      imageUrl: '0'
    }
  },
  mounted () {
    console.log(this)
  },
  methods: {
    write () {
      this.writing = false
      this.$nextTick(() => {
        this.writing = true
      })
    },
    async uploadImg (params) {
      try {
        const file = params.file
        this.imageUrl = URL.createObjectURL(file)
        this.write()
      } catch (error) {
        this.$errAlert(error)
      }
    },
    save () {
      const imgUrl = this.$refs.qrCode.saveImg()
      const imgLink = document.createElement('a')
      imgLink.download = `output.png`
      imgLink.style.display = 'none'
      imgLink.href = imgUrl
      document.body.appendChild(imgLink)
      imgLink.click()
      document.body.removeChild(imgLink)
    }
  }
}
</script>

<style lang="less" scoped>
.writer {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  .right {
    display: flex;
    align-items: center;
    flex-direction: column;
    height: 500px;
    justify-content: space-around;
    .upload {
      display: inline-block;
      margin: 0 10px;
    }
  }
  .qr_code {
    text-align: center;
    .desc {
      margin: 20px;
    }
  }
}
</style>
